import tempfile
import re
import subprocess
from chilin2.helpers import JinjaTemplateCommand, template_dump, json_dump, json_load

def stat_cor(input={"correlation_R":"", "cor_pdf": "", "venn": "", },
             output={"json": ""}, param=None):
    # TODO: merge this into stat_venn
    """ ReplicateQC aims to describe the similarity of replicate experiment. Venn diagram and correlation plot will be used."""
    result_dict = {"stat": {}, "input": input, "output": output, "param": param}

    with open(input["cor"], 'rU') as f:
        value = f.readline()
        values = value.strip().split()
    correlation_list = [float(i) for i in values[1:-1]]
    print(correlation_list)
    result_dict["stat"]["cor"] = correlation_list
    result_dict["stat"]["min_cor"] = min(correlation_list)

    result_dict["stat"]["judge"] = "Pass" if result_dict["stat"]["min_cor"] >= 0.6 else "Fail"
    result_dict["stat"]["cutoff"] = 0.6
    json_dump(result_dict)

def latex_cor(input, output, param):
    json_dict = json_load(input["json"])
    latex = JinjaTemplateCommand(
        name = "correlation",
        template = input["template"],
        param = {"section_name": "correlation",
                 "correlation_graph": json_dict["input"]["cor_pdf"],
                 "render_dump": output["latex"]})
    template_dump(latex)


def stat_venn(input={"venn": ""}, output={"json",""}, param=None):
    result_dict = {"stat": {}, "input": input, "output": output, "param": param}
    json_dump(result_dict)


def latex_venn(input, output, param):
    json_dict = json_load(input["json"])
    latex = JinjaTemplateCommand(
        name = "venn diagram latex",
        template = input["template"],
        param = {"section_name": "venn",
                 "venn_graph": json_dict["input"]["venn"],
                 "render_dump": output["latex"]})
    template_dump(latex)





